package xyz.fefine;

import javax.swing.*;
import java.io.*;

/**
 * Created by feng_ on 2016/8/31.
 */
public class CodeDialog extends Reader{

    private String buffer = null;
    private int pos = 0;

    /**
     * 读取len长度到buf中
     * @param buf 字符串
     * @param off 偏移量
     * @param len 长度
     * @return
     */
    public int read(char[] buf, int off, int len) {
        if (buffer == null) {
            //have bug,
            //当read没有关闭时，再次进行读取会执行read，然后再次打开窗口
            String in = showDialog();
            if (in == null) {
                return -1;
            } else {
                print("-----input text-----");
                print(in);
                print("-------end----------");
                buffer = in + "\n";
                pos = 0;
            }
            int size = 0;
            int lens = buffer.length();

            while (pos < lens && size < len){
                buf[off + size++] = buffer.charAt(pos++);

//            if (pos == lens) {
//                buffer = null;
//            }

            }
            return size;
        }

        return -1;
    }

    @Override
    public void close() throws IOException {

    }

    protected void print(String s) {
        System.out.println(s);
    }

    protected String showDialog() {
        JTextArea area = new JTextArea(20, 40);
        JScrollPane pane = new JScrollPane(area);
        int result = JOptionPane.showOptionDialog(null, pane, "INPUT",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE,
                null, null, null);
        if (result == JOptionPane.OK_OPTION) {
            return area.getText();
        } else {
            return null;
        }
    }

    public static Reader file() throws FileNotFoundException {
        JFileChooser chooser = new JFileChooser();
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            return new BufferedReader(new FileReader(chooser.getSelectedFile()));
        } else {
            throw new FileNotFoundException();
        }
    }

}
